package com.shajj.movie.fetch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.simpleds.bg.AbstractBackgroundTask;
import org.simpleds.bg.TaskRequest;

import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.shajj.movie.IdGenerator;
import com.shajj.movie.PMF;
import com.shajj.movie.Subtitle;

public class DataTask extends AbstractBackgroundTask {

    private static final Logger log = Logger.getLogger("shajj");

    private Pattern title = Pattern.compile("<span class=\"name_org\" id=\"movietitle1\">(.*?)</span>", Pattern.DOTALL);
    private Pattern time = Pattern.compile("<td>发布时间：</td><td colspan=\"3\">(.*?)</td>", Pattern.DOTALL);
    private Pattern source = Pattern.compile("<td>字幕来源：</td><td colspan=\"3\">(.*?)</td></tr>", Pattern.DOTALL);
    private Pattern uploader = Pattern.compile("<td>贡献者：</td><td colspan=\"3\">(.*?)</td>", Pattern.DOTALL);
    private Pattern fileSize = Pattern.compile("<em id=\"downsubbtnfsize\" style=\"float:right;margin:auto 12px auto auto\">(.*?)</em>", Pattern.DOTALL);
    private Pattern fileName = Pattern.compile("<td>字幕文件：</td><td colspan=\"3\"><div style=\"width:350px;word-wrap:break-word;overflow:hidden;\">(.*?)</div></td>", Pattern.DOTALL);
    private Pattern part = Pattern.compile("<td>版本分割：</td><td colspan=\"3\">(.*?)</td>", Pattern.DOTALL);
    private Pattern format = Pattern.compile("<td>字幕格式：</td><td class=\"subdes_td\">(.*?)</td>", Pattern.DOTALL);
    private Pattern language = Pattern.compile("<td class=\"subdes_th\">字幕语种：</td><td class=\"subdes_td\">(.*?)</td>", Pattern.DOTALL);

    private static final String target = "http://shooter.cn/xml/sub/";

    private static final String NOTFOUND = "服务页面没有找到";

    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private PersistenceManager persistenceManager;
    private Query singleQuery;

    public DataTask() {
        super("shajj");

        persistenceManager = PMF.get().getPersistenceManager();
        singleQuery = persistenceManager.newQuery(IdGenerator.class, "key == keyParam");
        singleQuery.declareParameters("String keyParam");
    }

    @SuppressWarnings("unchecked")
    @Override
    protected long doProceed(TaskRequest request) {
        // execute the query and locate the cursor, if any
        Long id = 1L;
        String idString = request.getParameter("id");
        if (idString != null && !idString.equals("")) {
            id = Long.parseLong(idString);
        } else {
            List<IdGenerator> list = (List<IdGenerator>) singleQuery.execute("subtitle");
            if (list != null && list.size() > 0) {
                id = list.get(0).getId();
            }
        }
        log.warning("Start perform thread NO." + id);
        if (id % 100 == 0) {
            saveId(id);
        }
        String content = getContent(id);
        if (!content.contains(NOTFOUND)) {
            try {
                Subtitle subtitle = makeSubtitle(id, content);
                if (subtitle != null) {
                    persistenceManager.makePersistent(subtitle);
                }
            } catch (Exception e) {
                log.severe(e.getMessage());
            }

            // invoke next
            request.setParameter("id", String.valueOf(++id));
            defer(request);
        } else {
            saveId(id);
            notifyFinalization();
        }
        return id;
    }

    private void saveId(Long id) {
        IdGenerator idGenerator = new IdGenerator("subtitle", ++id);
        try {
            persistenceManager.makePersistent(idGenerator);
        } catch (Exception e) {
            log.severe("存储id失败" + e.getMessage());
        }
    }

    private void defer(TaskRequest request) {
        TaskOptions url = TaskOptions.Builder.withUrl(request.getUri());
        for (String paramName : request.getParameterNames()) {
            url.param(paramName, request.getParameter(paramName));
        }
        QueueFactory.getDefaultQueue().add(url);
    }

    private Subtitle makeSubtitle(Long id, String content) {
        Subtitle subtitle = null;
        try {
            Matcher matcher = title.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle = new Subtitle(id, matcher.group(1));
                }
            }
            matcher = time.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    try {
                        subtitle.setTime(simpleDateFormat.parse(matcher.group(1)));
                    } catch (Exception e) {
                        subtitle.setTime(simpleDateFormat.parse("2001.12.21 03:41:15"));
                    }
                }
            }
            matcher = source.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setSource(matcher.group(1));
                }
            }
            matcher = uploader.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setUploader(matcher.group(1));
                }
            }
            matcher = fileName.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setFileName(matcher.group(1));
                }
            }
            matcher = fileSize.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setFileSize(matcher.group(1));
                }
            }
            matcher = part.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setPart(matcher.group(1));
                }
            }
            matcher = format.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setFormat(matcher.group(1));
                }
            }
            matcher = language.matcher(content);
            if (matcher.find()) {
                if (matcher.groupCount() > 0) {
                    subtitle.setLanguage(matcher.group(1));
                }
            }
        } catch (Exception e) {
            log.severe("正则匹配失败" + e.getMessage());
        }
        return subtitle;
    }

    private String getContent(Long id) {
        try {
            String prefix = String.valueOf(id / 1000);
            URL url = new URL(target + prefix + "/" + id + ".xml");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            return sb.toString();
        } catch (Exception e) {
            log.severe("获取页面信息错误" + e.getMessage());
        }

        return "";
    }


}
